'use strict';

const dataConst = require('../constant/data-const');

const Service = require('egg').Service;

class UserLabelService extends Service {
    async addUserLabelListSrv(userId, labelArray) {
        const { app } = this;

        const userLabelResult = await app.model.UserLabel.findAll({
            where: {
                user_id: userId
            }
        });

        for (const itemResult of userLabelResult) {
            const result = labelArray.some(item => item.value === itemResult.label_value);
            if (!result) {
                await app.model.UserLabel.destroy({
                    where: {
                        id: itemResult.id
                    }
                });
            }
        }

        for (const itemResult of labelArray) {
            const { type, value } = itemResult;
            const labelResult = await app.model.UserLabel.findOne({
                where: {
                    user_id: userId,
                    label_type: type,
                    label_value: value
                }
            });

            if (!labelResult) {
                await app.model.UserLabel.create({
                    user_id: userId,
                    label_type: type,
                    label_value: value
                });
            }
        }

        return await app.model.UserLabel.findAll({
            where: {
                user_id: userId
            },
            attributes: ['label_type', 'label_value']
        });
    }

    async getUserLabelListSrv(userId) {
        const { app } = this;

        return await app.model.UserLabel.findAll({
            where: {
                user_id: userId
            },
            attributes: ['label_type', 'label_value']
        });
    }
}

module.exports = UserLabelService;
